﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using DBUtility.PetaPoco;
using Model;

namespace DAL
{
	/// <summary>
    /// 已推送的消息 數據訪問類
    /// </summary>
    public class PushmessageDAL : BaseDAL<Model.Pushmessage>
    {
        /// <summary>
        /// 添加已推送消息以及已推送的設備
        /// </summary>
        /// <param name="AppId">項目名</param>
        /// <param name="Message">消息</param>
        /// <param name="DevicetokenList">設備集合</param>
        /// <param name="Type">類型</param>
        /// <returns></returns>
        public int AddList(int AppId, string Message, string DevicetokenList, int Type)
        {
            try
            {
                using (Transaction tran = db.GetTransaction())//开始事务
                {
                    Pushmessage model = new Pushmessage();
                    model.AppId = AppId;
                    model.MessageContent = Message;
                    model.SendTime = DateTime.Now;
                    #region 添加Pendingpushmessage
                    object objId = db.Insert(model);
                    if (objId == null || objId == DBNull.Value)
                    {
                        return 0;
                    }
                    #endregion

                    int id;
                    if (!int.TryParse(objId.ToString(), out id) || id == 0)
                    {
                        return 0;
                    }

                    object objIsSuccess = null;

                    string[] tokenList = DevicetokenList.Split(',');
                    #region 添加Able_Channel_Info
                    if (tokenList != null && tokenList.Length > 0)
                    {
                        foreach (var token in tokenList)
                        {
                            Sentdevice de = new Sentdevice();
                            de.MId = id;
                            de.Devicetoken = token;
                            de.Type = Type;
                            objIsSuccess = db.Insert(de);

                            if (objIsSuccess == null || objIsSuccess == DBNull.Value)
                            {
                                return 0;
                            }

                        }
                    }
                    #endregion

                    tran.Complete();//提交事务
                    return id;
                }
            }
            catch
            {
                return 0;
            }
        }
    }
}
